<template>
  <div ref="pdfRef" v-if="resumeData">
    <EN v-if="lang == 'en'" />
    <ZHCN v-if="lang == 'cn'" />
  </div>
</template>

<script setup lang="ts">
import { createPDF } from "jspdf-pro";
import {
  ExperienceUrl,
  postCertificateList,
  postExperienceList,
  postMemberIntention,
} from "../../../../api/profile";
import {
  defineAsyncComponent,
  inject,
  nextTick,
  onBeforeMount,
  onMounted,
  provide,
  ref,
  watch,
} from "vue";
import { postDownloadPdfCount } from "../../../../api/member";
import { message } from "ant-design-vue";
import { useRoute } from "vue-router";
const EN = defineAsyncComponent(() => import("./tepmlate/EN.vue"));
const ZHCN = defineAsyncComponent(() => import("./tepmlate/ZH_CN.vue"));

const fetching = inject("fetching");
const generating = inject("generating");
const route = useRoute();
const lang = route.query.lang as string;
const langList = ["cn", "en"];
onBeforeMount(() => {
  if (!langList.includes(lang)) {
    goto(-1);
    return;
  }
  getResumeData();
});
// 简历数据-pdf
const resumeData = ref();
provide("resumeData", resumeData);
const getResumeData = async () => {
  let res = await Promise.all([
    postCertificateList(),
    postMemberIntention(lang),
    postExperienceList(ExperienceUrl.workList, { lang }),
    postExperienceList(ExperienceUrl.eduList, { lang }),
    postExperienceList(ExperienceUrl.skillList, { lang }),
    postExperienceList(ExperienceUrl.honorList, { lang }),
  ]);
  resumeData.value = res;
  fetching.value = false;
};

const pdfRef = ref<HTMLElement | undefined>();
let isResetEditorClassName = false;
const generatePDF = async () => {
  if (!pdfRef.value) return;
  let res = await postDownloadPdfCount();
  if (res.code == 400) {
    message.warning(res.msg);
    goto("/pay");
    return;
  }
  if (!isResetEditorClassName) {
    initEditorDoms();
    isResetEditorClassName = true;
  }
  let fileName = "Resume-English(EN).pdf";
  generating.value = true;
  let marginOptions = {
    top: 0,
    bottom: 0,
  };
  if (lang == "cn") {
    fileName = "个人简历-中文(ZH-CN).pdf";
    marginOptions = {
      top: 10,
      bottom: 10,
    };
  }
  setTimeout(() => {
    nextTick(() => {
      createPDF(pdfRef.value!)
        .contentWidth(545.266)
        // 595.266
        .margin(marginOptions)
        .setClassControlFilter("isLeafWithoutDeepFilter", (v) =>
          ["divider-inside"].includes(v)
        )
        .onProgress((page, total) => {
          let percent = (page / total) * 100;
          
          if (percent == 100) {
            generating.value = false;
          }
        })
        .toPdf(fileName);
    });
  });
};

const initEditorDoms = () => {
  let ql_editor_boxs = pdfRef.value?.querySelectorAll(".ql-editor *");
  ql_editor_boxs?.forEach((element) => {
    if (element.lastChild?.nodeName == "#text") {
      element.classList.add("divider-inside");
    }
  });
};

defineExpose({
  generatePDF,
});
</script>
<style scoped lang="less"></style>
